class Solution
{
public:
    void wallsAndGates(vector<vector<int>> &rooms)
    {
        queue<array<int, 2>> q;
        int m = rooms.size();
        int n = rooms[0].size();
        for (int i = 0; i < m; ++i)
        {
            for (int j = 0; j < n; ++j)
            {
                if (rooms[i][j] == 0)
                {
                    q.push({i, j});
                }
            }
        }
        int dist = 0;
        while (!q.empty())
        {
            int qSize = q.size();
            ++dist;
            for (int i = 0; i < qSize; ++i)
            {
                auto [x, y] = q.front();
                q.pop();
                if (x > 0 && rooms[x - 1][y] == INT_MAX)
                {
                    rooms[x - 1][y] = dist;
                    q.push({x - 1, y});
                }
                if (x < m - 1 && rooms[x + 1][y] == INT_MAX)
                {
                    rooms[x + 1][y] = dist;
                    q.push({x + 1, y});
                }
                if (y > 0 && rooms[x][y - 1] == INT_MAX)
                {
                    rooms[x][y - 1] = dist;
                    q.push({x, y - 1});
                }
                if (y < n - 1 && rooms[x][y + 1] == INT_MAX)
                {
                    rooms[x][y + 1] = dist;
                    q.push({x, y + 1});
                }
            }
        }
    }
};